package com.rzcoding.config;

import com.alibaba.fastjson.JSON;
import com.rzcoding.client.UserFeign;
import com.rzcoding.entity.UserProfile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 用户信息服务
 * 实现 Spring Security的UserDetailsService接口方法，用于身份认证
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserFeign userFeign;

    /****
     * 根据用户名查找账户信息并返回用户信息实体
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserProfile userInfo = userFeign.findUserInfo(username);
        if (userInfo == null) {
            throw new UsernameNotFoundException("用户[" + username + "]不存在");
        } else {
            String pwd = userInfo.getPassword();
            String permissions = userInfo.getPermisssion();
            userInfo.setPassword(null);
            return new User(JSON.toJSONString(userInfo), pwd, AuthorityUtils.createAuthorityList(permissions));
        }
    }
}
